package b3.widget.match
{
	import b3.config.*;
	import b3.model.*;
	import b3.net.*;
	import b3.scene.*;
	import b3.scene.build.*;
	import b3.util.*;
	import b3.widget.*;
	import b3.widget.basic.*;
	import b3.widget.tab.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.filters.*;
	import flash.net.*;
	import flash.text.*;

	public class MatchTab extends Tab
	{
		private var match:Match;
		private var top3Container:Array;
		
		public function MatchTab(matchIndex:int)
		{
			match = new Match(matchIndex);
			var matchConfig:MatchConfig = Config.matchConfigs[matchIndex];
			super(matchConfig.name, 1, 1, 1);
			this.hidePageSelector();
			if (matchIndex > 0)
			{
				//建筑名称
				var notOpenText:TextField = new TextField();
				notOpenText.selectable = false;
	        	notOpenText.autoSize = TextFieldAutoSize.CENTER;
				notOpenText.defaultTextFormat = new TextFormat(BFont.fontName, 25, 0xFFFFFF, true);
				notOpenText.filters = [new GlowFilter(0x00AAFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
				notOpenText.x = 200;
				notOpenText.y = 100; 
				notOpenText.text = "尚未开启！敬请期待……";
				addChild(notOpenText);
				return;
			}
			//比赛对应建筑
			var buildingConfig:BuildingConfig = Config.buildingConfigs[matchConfig.buildingIndex];
			//图片
			var BuildingImage:Class = ResourceHelper.getInstance().getClassByName(buildingConfig.iconImage[matchConfig.roofType]);   
			var buildingImg:Sprite = new BuildingImage();
			buildingImg.mouseEnabled = false;
			buildingImg.alpha = 0.7;
			buildingImg.scaleX = 2.5;
			buildingImg.scaleY = buildingImg.scaleX;
			buildingImg.x = 100 - buildingImg.width / 2;
			buildingImg.y = 320 - buildingImg.height;
			addChild(buildingImg);
			//建筑名称
			var buildingTitleField:TextField = new TextField();
			buildingTitleField.selectable = false;
        	buildingTitleField.autoSize = TextFieldAutoSize.CENTER;
			buildingTitleField.defaultTextFormat = new TextFormat(BFont.fontName, 25, 0xFFFFFF, true);
			buildingTitleField.filters = [new GlowFilter(0x00AAFF, 1, 1.3, 1.3, 100, BitmapFilterQuality.HIGH)];
			buildingTitleField.x = 100;
			buildingTitleField.y = 0; 
			buildingTitleField.text = buildingConfig.name;
			addChild(buildingTitleField);
			//建筑描述
			var buildingDescripField:TextField = new TextField();
			buildingDescripField.selectable = false;
        	buildingDescripField.autoSize = TextFieldAutoSize.LEFT;
        	buildingDescripField.width = 180;
        	buildingDescripField.wordWrap = true;
			buildingDescripField.defaultTextFormat = new TextFormat(BFont.fontName, 15, 0xFFFFFF);
			buildingDescripField.x = 20;
			buildingDescripField.y = 40; 
			buildingDescripField.text = buildingConfig.description;
			addChild(buildingDescripField);
			//比赛排行、结果按钮
			var IconBgr:Class = ResourceHelper.getInstance().getClassByName("RankIcon");
			var buttonResult:BasicButton = new BasicButton(IconBgr);
			buttonResult.addEventListener(MouseEvent.CLICK, onButtonResultClick);
			buttonResult.alpha = 0.7;
			buttonResult.x = 230;
			buttonResult.y = 85;
			buttonResult.width = 150;
			buttonResult.scaleY = buttonResult.scaleX;
			addChild(buttonResult);
			//比赛排行说明
			var rankBriefField:TextField = new TextField();
			rankBriefField.selectable = false;
        	rankBriefField.autoSize = TextFieldAutoSize.LEFT;
			rankBriefField.defaultTextFormat = new TextFormat(BFont.fontName, 11, 0xFFFFFF);
			rankBriefField.x = 260;
			rankBriefField.y = 175; 
			rankBriefField.text = "      今日排名\n点击查看详细排名";
			addChild(rankBriefField);
			//比赛时间
			var matchTimeField:TextField = new TextField();
			matchTimeField.selectable = false;
        	matchTimeField.autoSize = TextFieldAutoSize.LEFT;
			matchTimeField.defaultTextFormat = new TextFormat(BFont.fontName, 15, 0xFFFFFF, true);
			matchTimeField.x = 225;
			matchTimeField.y = 220; 
			matchTimeField.htmlText = "<font color='#0055FF'>比赛时间</font>  " + formatTime(matchConfig.matchTime[0]) + "-" + formatTime(matchConfig.matchTime[1]);
			addChild(matchTimeField);
			//参赛条件
			var requireLevelField:TextField = new TextField();
			requireLevelField.selectable = false;
        	requireLevelField.autoSize = TextFieldAutoSize.LEFT;
			requireLevelField.defaultTextFormat = new TextFormat(BFont.fontName, 15, 0xFFFFFF, true);
			requireLevelField.x = 225;
			requireLevelField.y = 240; 
			requireLevelField.htmlText = "<font color='#0055FF'>参赛条件</font>  城市等级" + matchConfig.requireLevel[0] + "-" + matchConfig.requireLevel[1];
			addChild(requireLevelField);
			//参加按钮
			var ButtonBgr:Class = ResourceHelper.getInstance().getClassByName("ButtonBgr1");
			var buttonAttend:BasicButton = new BasicButton(ButtonBgr, "立即参加");
			buttonAttend.addEventListener(MouseEvent.CLICK, onButtonAttendClick);
			buttonAttend.x = 270;
			buttonAttend.y = 280;
			addChild(buttonAttend);
			this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			this.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
			//初始化Top3
			const pos:Array = [[270, 0], [320, 20], [215, 40]];
			top3Container = new Array();
			for (var i:int = 0; i < 3; i++)
			{
				var container:Sprite = new Sprite();
				container.x = pos[i][0];
				container.y = pos[i][1];
				addChild(container);
				loadTopPlayer(container, null);
				top3Container.push(container);
			}  
		}
		
		private function onAddedToStage(event:Event):void
		{
			match.loadMatchTop3(true);
			match.addEventListener(ModelEvent.REFRESH_MATCH_TOP3, onRefreshMatchTop3);
		}

		private function onRemovedFromStage(event:Event):void
		{
			match.removeEventListener(ModelEvent.REFRESH_MATCH_TOP3, onRefreshMatchTop3);
		}
		
		private function onRefreshMatchTop3(event:ModelEvent):void
		{
			for (var i:int = 0; i < match.top3.length; i++)
			{
				var rank:RankInfo = match.top3[i];
				var container:Sprite = top3Container[rank.ranking];
				loadTopPlayer(container, rank);
			}	
		}
		
		//格式化时间
		private function formatTime(minutes:int):String
		{
			var honours:int = minutes / 60;
			minutes = minutes % 60;
			return (honours < 10 ? "0" : "") + honours + ":" + (minutes < 10 ? "0" : "") + minutes;
		}
		
		//加载排名
		private function loadTopPlayer(container:Sprite, rank:RankInfo):void
		{
			//清空原来位置
			while (container.numChildren > 0)
				container.removeChildAt(0);
			//加载用户头像
			if (rank != null)
			{
				var pictLdr:Loader = new Loader();
				var pictURLReq:URLRequest = new URLRequest(rank.figureurl);
				pictLdr.load(pictURLReq);
				pictLdr.x = 10;
				pictLdr.y = 20;
				container.addChild(pictLdr);
				var maskSprite:Sprite = new Sprite();
				maskSprite.graphics.beginFill(0x000000);
				maskSprite.graphics.drawCircle(25, 25, 25);
				maskSprite.graphics.endFill();
				maskSprite.x = 10;
				maskSprite.y = 20;
				container.addChild(maskSprite);
				pictLdr.mask = maskSprite;
			}
			else
			{
				var JohnDoe:Class = ResourceHelper.getInstance().getClassByName("JohnDoe");
				var johnDoe:Sprite = new JohnDoe();
				johnDoe.x = 10;
				johnDoe.y = 20;
				johnDoe.width = 50;
				johnDoe.scaleY = johnDoe.scaleX;
				container.addChild(johnDoe);
			}
			//用户名字
			var userName:TextField = new TextField();
        	userName.autoSize = TextFieldAutoSize.CENTER;
			userName.selectable = false;
			userName.defaultTextFormat = new TextFormat("微软雅黑", 12, 0xFFFFFF, true);
			userName.x = 35;
			userName.y = 0;
			userName.text = (rank == null ? "未知" : rank.name.substr(0,4));
			container.addChild(userName);
			//用户人口
			var populationPane:Sprite = new Sprite();
			var PopulationIcon:Class = ResourceHelper.getInstance().getClassByName("PopulationIcon");
			var populationIcon:Sprite = new PopulationIcon();
			populationIcon.width = 25;
			populationIcon.scaleY = populationIcon.scaleX;
			populationIcon.x = -5;
			populationIcon.y = -2;
			populationPane.addChild(populationIcon);
			var populationText:TextField = new TextField();
        	populationText.autoSize = TextFieldAutoSize.LEFT;
			populationText.selectable = false;
			populationText.defaultTextFormat = new TextFormat("微软雅黑", 12, 0xFFFFFF, true);
			populationText.x = 17;
			populationText.y = 0;
			populationText.text = (rank == null ? "???" : rank.score.toString());
			populationPane.addChild(populationText);
			populationPane.x = 35 - populationPane.width / 2;
			populationPane.y = 68;
			container.addChild(populationPane);
		} 
		
		private function onButtonResultClick(event:MouseEvent):void
		{
			var matchResultDialog:MatchResultDialog = new MatchResultDialog(match);
			matchResultDialog.x = -matchResultDialog.width / 2;
			matchResultDialog.y = -matchResultDialog.height / 2;
			WidgetManager.getInstance().popOut([matchResultDialog], true);
		}
		
		private function onButtonAttendClick(event:MouseEvent):void
		{
			var me:Player = PlayerManager.getInstance().me;
			var myCityLevel:int = Config.getLevel(ObjConfig.POPULATION, me.packageModel.getObjectNum(ObjConfig.POPULATION)); 
			var matchConfig:MatchConfig = Config.matchConfigs[match.index];
			var popMessage:PopMessage;
			//检查比赛时间
			var currentMinutes:int = ServerRequest.currentSeconds() / 60 % (24 * 60); 
			if (currentMinutes < matchConfig.matchTime[0])
			{
				popMessage = new PopMessage("未到比赛开始时间，请耐心等待", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			else if (currentMinutes > matchConfig.matchTime[1])
			{
				popMessage = new PopMessage("比赛时间已过，请明天再来", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			//检查参赛城市等级
			else if (myCityLevel < matchConfig.requireLevel[0])
			{
				popMessage = new PopMessage("城市等级不足，请先提高人口", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			else if (myCityLevel > matchConfig.requireLevel[1])
			{
				popMessage = new PopMessage("城市等级已高于此级别，请参加高级别比赛", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
			else
			{
				match.addEventListener(ModelEvent.CHECK_MATCH_QUALIFICATION_COMPLETE, onCheckMatchQualificationComplete);
				match.checkMatchQualification();
			}
		}
		
		//Fix bug: 稳定卡对比赛影响过于大，可以无限继续
		private function getRidOfStable(state:StateModel):void
		{
			for (var i:int = 0; i < state.stateList.length; i++)
			{
		 		var stateInfo:StateInfo = state.stateList[i];
		 		var stateConfig:StateConfig = Config.stateConfigs[stateInfo.state];
		 		if (stateConfig.effectIndex == StateConfig.EFFECT_STABLE)
		 		{
		 			state.stateList[i] = null;
		 		}
			}
		}
		
		private function onCheckMatchQualificationComplete(event:ModelEvent):void
		{
		 	var me:Player = PlayerManager.getInstance().me;
			match.removeEventListener(ModelEvent.CHECK_MATCH_QUALIFICATION_COMPLETE, onCheckMatchQualificationComplete);
			var data:Object = event.data;
			if (data != null && data['qualified'])
			{
				var oldState:StateModel = new StateModel(me.userId);
				oldState.handleLoadStates(data['oldState']);
				//去除稳定状态
				getRidOfStable(oldState);
				SceneManager.getInstance().loadScene(BuildScene.getInstance());
				BuildScene.getInstance().changeParamByState(oldState);
				BuildScene.getInstance().startMatch(match);
			}
			else
			{
				var popMessage:PopMessage = new PopMessage("今日已经3度进入日排行，请明天再来~", 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage]);
			}
		}
	}
}